package com.cskaoyan.controller;

/**
 * @author lxy
 * @create 2021-10-21 11:12
 */

import com.cskaoyan.bean.basebean.BasePageData;
import com.cskaoyan.bean.basebean.BaseParam;
import com.cskaoyan.bean.basebean.BaseRespVo;
import com.cskaoyan.bean.user.Address;
import com.cskaoyan.exception.AddressException;
import com.cskaoyan.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * wx地址管理
 */
@RestController
@RequestMapping("wx/address")
public class WxAddressController {

    @Autowired
    AddressService addressService;

    // 查询所有地址信息
    @RequestMapping("list")
    public BaseRespVo list(BaseParam baseParam) {
        BasePageData data = addressService.queryAddressInWx(baseParam);
        return BaseRespVo.ok(data);
    }

    // 回显一个地址的详细信息
    @RequestMapping("detail")
    public BaseRespVo detail(Integer id) {
        Address address = addressService.detailAddress(id);
        return BaseRespVo.ok(address);
    }

    // 添加或者修改地址
    @PostMapping("save")
    public BaseRespVo save(@RequestBody Address address) throws AddressException {

        String tel = address.getTel();
        if (!tel.matches("^((13[0-9])|(14[0-9])|(15[0-9])|(17[0-9])|(18[0-9]))\\d{8}$")) {
            return BaseRespVo.fail401("手机号码格式不对!");
        }

        Integer id = address.getId();
        if (id == 0) {
            addressService.createAddress(address);
            return BaseRespVo.ok(id);
        }
        addressService.updateAddress(address);
        return BaseRespVo.ok(id);
    }

    // 删除地址
    @PostMapping("delete")
    public BaseRespVo delete(@RequestBody Map map) throws AddressException {
        Integer id = (Integer) map.get("id");
        addressService.deleteAddress(id);
        return BaseRespVo.ok();
    }
}
